package com.appos.service;

import com.alibaba.fastjson.JSONArray;
import com.appos.common.constant.HttpStatus;
import com.appos.common.core.page.PageDomain;
import com.appos.common.core.page.TableDataInfo;
import com.appos.common.core.page.TableSupport;
import com.appos.common.utils.StringUtils;
import com.appos.domain.Book;
import com.appos.domain.DynamicCollections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

@Service
public class MongoDbService {

    private static final Logger logger = LoggerFactory.getLogger(MongoDbService.class);

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存对象
     * @param book
     * @return
     */
    public String saveObj(Book book) {
        book.setCreateTime(new Date());
        book.setUpdateTime(new Date());
        mongoTemplate.save(book);
        return "添加成功";
    }

    public int createAutoTask(String collectionsName, DynamicCollections dynamicCollections) {
        mongoTemplate.save(dynamicCollections, collectionsName);
        return 1;
    }

    /**
     * 查询所有
     * @return
     */
    public TableDataInfo findList(String collectionsName) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        List list = Collections.EMPTY_LIST;
        long totalCount = 0;
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            Query query = new Query();

            totalCount = mongoTemplate.count(query, DynamicCollections.class, collectionsName);

            query.with(Sort.by(Sort.Direction.DESC, "createTime"));
            query.skip(pageSize*(pageNum-1)).limit(pageSize);

            list = mongoTemplate.find(query, DynamicCollections.class, collectionsName);
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(totalCount);
        return rspData;
    }

    /**
     * 删除
     * @return
     */
    public int del(String collectionsName, JSONArray uuids){
        uuids.forEach(uuid -> {
            Query query = new Query(Criteria.where("uuid").is(uuid));
            DynamicCollections dynamicCollections = mongoTemplate.findOne(query, DynamicCollections.class, collectionsName);
            mongoTemplate.remove(dynamicCollections, collectionsName);
        });
        return 1;
    }

    /**
     * 查询所有
     * @return
     */
    public List<Book> findAll() {
        return mongoTemplate.findAll(Book.class);
    }

    /***
     * 根据id查询
     * @param id
     * @return
     */
    public Book getBookById(String id) {
        Query query = new Query(Criteria.where("_id").is(id));
        return mongoTemplate.findOne(query, Book.class);
    }

    /**
     * 根据名称查询
     *
     * @param name
     * @return
     */
    public Book getBookByName(String name) {
        Query query = new Query(Criteria.where("name").is(name));
        return mongoTemplate.findOne(query, Book.class);
    }

    /**
     * 更新对象
     *
     * @param book
     * @return
     */
    public String updateBook(Book book) {
        Query query = new Query(Criteria.where("_id").is(book.getId()));
        Update update = new Update().set("publish", book.getPublish()).set("info", book.getInfo()).set("updateTime",
                new Date());
        // updateFirst 更新查询返回结果集的第一条
        mongoTemplate.updateFirst(query, update, Book.class);
        // updateMulti 更新查询返回结果集的全部
        // mongoTemplate.updateMulti(query,update,Book.class);
        // upsert 更新对象不存在则去添加
        // mongoTemplate.upsert(query,update,Book.class);
        return "success";
    }

    /***
     * 删除对象
     * @param dynamicCollections
     * @return
     */
    public String deleteDynamicCollections(DynamicCollections dynamicCollections) {
        mongoTemplate.remove(dynamicCollections);
        return "success";
    }

    /**
     * 模糊查询
     * @param search
     * @return
     */
    public List<Book> findByLikes(String search){
        Query query = new Query();
        Criteria criteria = new Criteria();
        //criteria.where("name").regex(search);
        Pattern pattern = Pattern.compile("^.*" + search + ".*$" , Pattern.CASE_INSENSITIVE);
        criteria.where("name").regex(pattern);
        List<Book> lists = mongoTemplate.findAllAndRemove(query, Book.class);
        return lists;
    }

}
